﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Island;

public class Actor : MonoBehaviour {

    [System.NonSerialized]
    public Account account = new Account();
    [System.NonSerialized]
    public Location location = new Location();

#if TEST
    public bool updatePosition;
    public bool isself;
    public void Awake()
    {
        if (isself)
        {
            ActorManager.Instance.LocalID = "1001";
            ActorManager.Instance.AddActor("1001", this);
        }
    }
    private void Start()
    {
        if (updatePosition)
        {
            Actor localActor = ActorManager.Instance.GetLocal();
            Vector3 realPos = GPSTool.GetUnityVector3(this.location, localActor.location);
            this.transform.position = realPos;
        }
    }
#endif

    public void StartGPS()
    {
        if(Application.isMobilePlatform)
        {
            GPSTool.Instance.GetLocation(LocationCallback);
        }
    }

    public void StopGPS()
    {
        GPSTool.Instance.Stop();
    }

    IEnumerator LoopGetGPS()
    {
        Debug.Log("LoopGetGPS");
        while (true)
        {
            GPSTool.Instance.GetLocation((n, e, t) =>
        {
            if (location.latitude != n || location.longitude != e)
            {
                location.latitude = n;
                location.longitude = e;

                AyncLocation();
            }
        });

            yield return new WaitForSeconds(1);
        }
    }


    void LocationCallback(float e, float n, double t)
    {
        location.latitude = n;
        location.longitude = e;

        AyncLocation();
    }

    void AyncLocation()
    {
        Debug.Log("N:" + (location.latitude) + " E:" + (location.longitude));

        //发送服务器
        PBLocation pb = location.ToPB();
        pb.id = ActorManager.Instance.LocalID;
        NetworkManager.Instance.Send(Protocol.ReqLocation, pb);
    }

    public void SetLocation(PBLocation pb)
    {
        location.ParsePB(pb);

        Actor localActor = ActorManager.Instance.GetLocal();
        Vector3 realPos = GPSTool.GetUnityVector3(this.location, localActor.location);
        //看向自己
        transform.LookAt(Vector3.zero);
        //距离+2
        Vector3 offset = realPos.normalized * 2;
        this.transform.position = realPos+ offset;
    }
}
